package com.timedomain.him.remake.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.Toast;

import com.timedomain.him.remake.Program;
import com.timedomain.him.remake.R;
import com.timedomain.him.remake.utils.*;

import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.zip.DeflaterOutputStream;

public class SettingActivity extends BaseActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
    }

    public void btnMorningCallTriggerMode(View view) {
        new AlertDialog.Builder(this)
                .setMessage("早安电话触发：\n" +
                        "旧版"+(AppSettings.morningCallIsManual ? "" : "(当前)")+"：不需要进行晚安对话\n" +
                        "新版"+(AppSettings.morningCallIsManual ? "(当前)" : "")+"：需要进行晚安对话并约定时间之后才会接到（凌晨四点之前）\n")
        .setPositiveButton("新版", (dialog, which) -> {
            AppSettings.morningCallIsManual = true;
            AppSettings.saveSettings(SettingActivity.this);
            MorningCallManager.setNextMorningCall(SettingActivity.this);
        }).setNegativeButton("旧版", (dialog, which) -> {
            AppSettings.morningCallIsManual = false;
            AppSettings.morningCallDateStamp = TimeUtils.toDateStamp(TimeUtils.getTimeStampIgnoreTimeZone());
            AppSettings.saveSettings(SettingActivity.this);
            MorningCallManager.setNextMorningCall(SettingActivity.this);
        }).create().show();
    }

    public void btnMorningCallSetTime(View view) {
        startActivity(new Intent(this,MorningCallActivity.class));
        finish();
    }

    private static final String currentMark = " (当前)";

    public void btnNightModeDuration(View view) {
        final String[] items = new String[]{"20分钟","30分钟","45分钟","60分钟"};
        for (int i = 0; i < items.length; i++) {
            if( Integer.parseInt(items[i].replace("分钟","")) == AppSettings.nightModeDuration){
                items[i] = items[i]+currentMark;
            }
        }
        new AlertDialog.Builder(this).setTitle("晚安模式时长").setItems(items, (dialog, which) -> {
            int newMin = Integer.parseInt(items[which].replace("分钟","").replace(currentMark,""));
            AppSettings.nightModeDuration = newMin;
            AppSettings.saveSettings(SettingActivity.this);
        }).setNegativeButton("取消",null).create().show();
    }

    public void btnNightModeStoryCount(View view) {

        String[] items = new String[]{"2个","3个","4个","5个"};
        for (int i = 0; i < items.length; i++) {
            if( Integer.parseInt(items[i].replace("个","")) == AppSettings.nightModeStoryCount){
                items[i] = items[i]+ currentMark;
            }
        }
        new AlertDialog.Builder(this).setTitle("晚安模式故事数量").setItems(items, (dialog, which) -> {
            int newMin = Integer.parseInt(items[which].replace("个","").replace(currentMark,""));
            AppSettings.nightModeStoryCount = newMin;
            AppSettings.saveSettings(SettingActivity.this);
        }).setNegativeButton("取消",null).create().show();
    }

    public void btnNightModeExcludedStories(View view) {
        List<String> paths = FileUtils.getAllNightStories();
        String[] displayTitle = new String[paths.size()];
        boolean[] checkState = new boolean[paths.size()];

        for (int i = 0; i < paths.size(); i++) {

            displayTitle[i] = FileUtils.getFileNameWithoutExtension(paths.get(i));
            checkState[i] = AppSettings.filteredNightStories.contains(paths.get(i));
        }

        new AlertDialog.Builder(this).setTitle("选择晚安模式中不想要出现的故事").setMultiChoiceItems(displayTitle, checkState, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                checkState[which] = isChecked;
            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                List<String> toRemove = new ArrayList<>();
                for (int i = 0; i < checkState.length; i++) {
                    if(checkState[i]){
                        toRemove.add(paths.get(i));
                    }
                }
                if(toRemove.size() + 5 > paths.size()){
                    showToast("需要至少五个故事。");
                    return;
                }
                AppSettings.filteredNightStories.clear();
                AppSettings.filteredNightStories.addAll(toRemove);
                AppSettings.saveSettings(SettingActivity.this);
            }
        }).create().show();

    }

    public void btnAbout(View view) {
        startActivity(new Intent(this,AboutActivity.class));
    }



    public void showNotificationSettings(View view) {
        NotificationUtils.showNotificationSetting(this);
    }


    public void clearChatlog(View view) {
        new AlertDialog.Builder(this)
                .setMessage("是否清空聊天记录？")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DB.ChatMessage.Clear();
                        showToast("清理完成");
                    }
                }).setNegativeButton(android.R.string.no,null).create().show();
    }


    public void showBackgroundSettings(View view) {
        startActivity(new Intent(this,BackgroundActivateSettingsActivity.class));
    }

    public void btnNightModeVolumeAdjustment(View view) {
        String[] items = new String[]{"15%","20% (降噪耳机)","25%","30%","40% (普通耳机，手机外放)","60%","75%","80%","100% (音响)"};

        for (int i = 0; i < items.length; i++) {
            float targetValue = (float)Integer.parseInt(items[i].split(Pattern.quote("%"))[0]) / 100f * 0.25f;
            if(Math.abs(targetValue - AppSettings.nightModeVolumeAdjustment) < 0.0001){
                items[i] =  items[i] + currentMark;
            }
        }

        new AlertDialog.Builder(this).setTitle("晚安模式呼吸声音量调整").setItems(items, (dialog, which) -> {
            float newMin = Integer.parseInt(items[which].replace(currentMark,"").split(Pattern.quote("%"))[0]);
            AppSettings.nightModeVolumeAdjustment = newMin / 100f * 0.25f;
            AppSettings.saveSettings(SettingActivity.this);
        }).setNegativeButton("取消",null).create().show();
    }

    public void btnNightModeBatteryOptimization(View view) {
        new AlertDialog.Builder(this)
                .setTitle("晚安模式省电设置：")
                .setMessage(
                        "开启省电时，若晚安模式中没有接入充电器，则晚安模式结束45分钟后会自动退出晚安模式。\n\n" +
                        "开启此功能可以防止忘记接入充电器时第二天早上手机没电的情况。\n\n" +
                        "如果您的手机电池特别庞大，或者正在使用安卓模拟器，可以关闭这个功能。\n\n目前已"+(AppSettings.nightModeIgnoreBattery ? "关闭" : "开启")+"省电模式。")
                .setPositiveButton("开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        AppSettings.nightModeIgnoreBattery = false;
                        AppSettings.saveSettings(SettingActivity.this);
                    }
                }).setNegativeButton("关闭", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                AppSettings.nightModeIgnoreBattery = true;
                AppSettings.saveSettings(SettingActivity.this);
            }
        }).create().show();
    }

    public static int WRITE_REQUEST_CODE = 297581;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
        super.onActivityResult(requestCode, resultCode, resultData);
        if (requestCode == WRITE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            if (resultData != null) {
                //获取Uri
                Uri uri = resultData.getData();
                if (requestCode == WRITE_REQUEST_CODE) {
                    saveFile(uri);
                }
            }
        }
    }

    void saveFile(Uri uri){
        RunUtils.runProgressDialog(this,"正在导出存档...",()->{
            try {
                PrintStream printStream = new PrintStream((getContentResolver().openOutputStream(uri)));
                printStream.println(BackupRestoreUtils.dumpData(SettingActivity.this));
                printStream.flush();
                printStream.close();

                if(isLogout){
                    DB.MorningCall.Clear();
                    DB.ChatMessage.Clear();
                    DB.CompanionPhoneCall.Clear();
                    SettingUtils.saveAllSetting(this, AppSettings.SettingHolderObject.class,false,new AppSettings.SettingHolderObject());
                    AppSettings.loadSettings(this);
                    MorningCallManager.setNextMorningCall(this);
                    SpecialEventManager.checkHasSpecialEvent(this);
                }

                runOnUiThread(() -> {
                    showToast("存档导出完成");
                    if(isLogout){
                        finish();
                    }

                });

            } catch (FileNotFoundException|IllegalAccessException e) {
                e.printStackTrace();
                runOnUiThread(() -> showToast("无法导出存档文件"));
            }
        });
    }

    private boolean isLogout = false;

    // TODO: 制作存档转移的图文教程 (可以放在外部网页上，方便查看)

    public void btnLogoutClick(View view) {
        new AlertDialog.Builder(this).setTitle("退出登录").setMessage("是否导出存档并退出登录？").setPositiveButton(android.R.string.yes, (dialog, which) -> {
            exportData(view);
            isLogout = true;
        }).setNegativeButton(android.R.string.no,null).create().show();

    }
    public void exportData(View view) {
        isLogout = false;
        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("application/json");
        intent.putExtra(Intent.EXTRA_TITLE, "「他」存档数据_"+(new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()))+".json");
        startActivityForResult(intent, WRITE_REQUEST_CODE);
    }

    public void openDataMigrantTutorial(View v){
        gotoUrl("https://himremake.zyfdroid.com/help_backup.html");
    }

    public void debugTest(View v){

    }

    public void manageDatapack(View view) {
        DataPackActivity.startNoDatapack(this);
    }
}
